#!/bin/bash

function error()
{
    echo "postinstall error!" "$1" 
    exit
}

#
# The shell app allows the user to select the original application that will be
# updated. It then writes the name of the original app and the path of the
# app into two separate files.
#

AppName="`cat /tmp/MacSoftInstaller/_AppName.txt`"
AppPath="`cat /tmp/MacSoftInstaller/_AppPath.txt`"
AppParent="`cat /tmp/MacSoftInstaller/_AppParent.txt`"
GameDataName="`cat /tmp/MacSoftInstaller/_GameDataName.txt`"
AppInPackage="`cat /tmp/MacSoftInstaller/_AppInPackage.txt`"

echo Selected app to be updated: $AppPath$AppName


#
# On 10.3.9, the Installer doesn't seem to join resource and data forks back
# together until after the scripts are run. Thus, any resource files that we
# ditto in this script will be bad. So before doing anything, we look for all
# resource files and join them back together.
#

find "/tmp/MacSoftInstaller" -type d | while read dir ; do
	/System/Library/CoreServices/FixupResourceForks "$dir"
done


#
# Copy the new application from /tmp/MacSoftInstaller/ to the same level as the old game folder
#

ditto -V --rsrc "/tmp/MacSoftInstaller/$AppInPackage" "$AppParent$AppInPackage"


#
# Copy the contents of the old game folder to the new app's GameData folder
#

ditto -V --rsrc "$AppPath" "$AppParent$AppInPackage/Contents/Resources/$GameDataName"


#
# Update the GameData folder with any new files we included
#

find "/tmp/MacSoftInstaller/$GameDataName" -type f | while read file ; do
	[ "$file" -nt "$AppParent$AppInPackage/Contents/Resources/${file:22}" ] && ditto -V --rsrc "$file" "$AppParent$AppInPackage/Contents/Resources/${file:22}" 
done

#
# ditto is great, however it has some problems.  If you ditto a file that doesn't have
# a parent directory, ditto will create that directory for you, but will leave off
# some of the write permissions. So after we're done copying the new GameData
# files, walk through the directory structure and make sure all the dirs have
# the same permissions.
#

#
# Note: This would normally be 775. But we use 777 for AoM because the game has to saves files
# to the GameData folder, so we give extra access to non-Admin users
#

find "$AppParent$AppInPackage/Contents/Resources/$GameDataName" -type d | while read dir ; do
	chmod 777 "$dir"
done

#
# Delete the original app from the GameData folder
#

rm -v "$AppParent$AppInPackage/Contents/Resources/$GameDataName/$AppName"

#
# Delete the original folder
#

rm -R "$AppPath"

#
# Touch the app so the Finder will show the updated version number
#

touch "$AppParent$AppInPackage"

#
# Clean up the /tmp folder
#

rm -r "/tmp/MacSoftInstaller"/*

exit 0
